package com.os.service;

import com.os.dao.PersonRepository;
import com.os.entity.Person;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;

@Service
public class DemoServiceImpl implements DemoService{

    @Autowired
    private PersonRepository personRepository;

    @Transactional(rollbackOn={IllegalArgumentException.class})  //指定特定异常时候，数据回滚
    @Override
    public Person savePersonWithRollBack(Person person) {
        Person person1 = personRepository.save(person);

        if(person.getName().equals("Matt")){
            throw new IllegalArgumentException("Matt已存在，数据将回滚！");
        }
        return person1;
    }

    @Transactional(dontRollbackOn={IllegalArgumentException.class})  //指定特定异常的时候，数据不回滚
    @Override
    public Person savePersonWithoutRollBack(Person person) {
        Person person1 = personRepository.save(person);

        if(person.getName().equals("Matt")){
            throw new IllegalArgumentException("Matt虽已经存在，数据将不会回滚！");
        }
        return person1;
    }

    @Override
    @CachePut(value="people", key="#person.id")  //缓存新增的数据，缓存名称为people，数据的key为person的id
    public Person save(Person person) {
        Person p = personRepository.save(person);
        System.out.println("为id、key为：" + p.getId() + "数据做了缓存");
        return p;
    }

    @Override
    @CacheEvict(value="people")  //从缓存people中删除key为id的数据
    public void remove(Long id) {
        System.out.println("删除id、key为" + id + "的数据缓存");
        personRepository.deleteById(id);
    }

    @Override
    @Cacheable(value="people", key="#person.id")  //缓存key为id的数据缓存people中
    public Person findOne(Person person) {
        Person p = personRepository.getById(person.getId());
        System.out.println("为id、key为" + p.getId() + "数据做了缓存");
        return p;
    }
}
